# 配置项容器模块
from PyQt6.QtWidgets import QWidget, QHBoxLayout, QSpacerItem, QSizePolicy
from PyQt6.QtCore import Qt
from typing import Optional, Dict
from ..base_modules.type_module import TypeModule
from ..base_modules.prompt_module import PromptModule
from ..base_modules.help_module import HelpModule
from parser.config_model import ConfigItem
from PyQt6.QtWidgets import QLabel, QVBoxLayout


class ConfigContainerModule:
    """配置项容器模块"""

    def __init__(self):
        self.type_module = TypeModule()
        self.prompt_module = PromptModule()
        self.help_module = HelpModule()
        self.containers: Dict[str, QWidget] = {}
        self.controls: Dict[str, QWidget] = {}

    def create_container(
        self, config_item: ConfigItem, parent: QWidget = None
    ) -> QWidget:
        """创建配置项容器"""
        container = QWidget(parent)
        container.setObjectName(f"config-container-{config_item.id}")
        container.setStyleSheet(
            """
            QWidget#config-container-{id} {{
                padding: 4px;
                border-bottom: 1px solid #f0f0f0;
            }}
            QWidget#config-container-{id}.disabled {{
                opacity: 0.6;
            }}
        """.format(
                id=config_item.id
            )
        )

        layout = QHBoxLayout(container)
        layout.setContentsMargins(8, 6, 8, 6)
        layout.setSpacing(10)

        # 创建提示文本（主提示 + 次级元信息）
        prompt_text = config_item.properties.prompt or config_item.name
        prompt_label = self.prompt_module.create_prompt(prompt_text)
        prompt_label.setMinimumWidth(200)
        prompt_label.setStyleSheet('font-weight: bold;')
        # 让提示文本在水平方向可扩展，避免与右侧控件重叠
        prompt_label.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Preferred)

        # 次级信息（默认值 / 范围 / 简短 help 预览）
        meta_parts = []
        try:
            if config_item.properties.default is not None:
                meta_parts.append(f"default: {config_item.properties.default.value}")
        except Exception:
            pass
        try:
            if config_item.properties.range is not None:
                r = config_item.properties.range
                meta_parts.append(f"range: {r.min}-{r.max}")
        except Exception:
            pass
        try:
            if config_item.properties.help:
                h = str(config_item.properties.help).strip()
                first_line = h.splitlines()[0] if h else ''
                if first_line:
                    meta_parts.append(first_line if len(first_line) < 80 else first_line[:77] + '...')
        except Exception:
            pass

        meta_label = QLabel('  '.join(meta_parts))
        meta_label.setWordWrap(True)
        meta_label.setStyleSheet('color: #666; font-size: 11px;')
        meta_label.setContentsMargins(0, 4, 0, 0)
        # 次级信息也允许扩展，避免与控件区域冲突
        meta_label.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Preferred)

        prompt_area = QWidget()
        prompt_area_layout = QVBoxLayout(prompt_area)
        prompt_area_layout.setContentsMargins(0, 0, 0, 0)
        prompt_area_layout.setSpacing(6)
        prompt_area_layout.addWidget(prompt_label)
        if meta_parts:
            prompt_area_layout.addWidget(meta_label)

        layout.addWidget(prompt_area)

        # 创建配置控件
        control_container, control = self.type_module.create_control(
            config_item.properties.type or "bool", config_item.current_value
        )
        # 控件区域设置为尽量紧凑，避免侵占文本区域
        control_container.setSizePolicy(QSizePolicy.Policy.Minimum, QSizePolicy.Policy.Preferred)
        layout.addWidget(control_container)

        # 设置伸缩因子：文本区域更宽，控件区域保持紧凑
        layout.setStretch(0, 3)
        layout.setStretch(1, 1)

        # 添加水平间隔，将帮助按钮推到右侧
        spacer = QSpacerItem(
            40, 20, QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Minimum
        )
        layout.addItem(spacer)

        # 创建帮助按钮
        if config_item.properties.help:
            help_button = self.help_module.create_help_button(
                config_item.properties.help, parent
            )
            layout.addWidget(help_button)

        # 保存引用
        self.containers[config_item.id] = container
        self.controls[config_item.id] = control

        # 设置初始状态
        self.set_container_enabled(config_item.id, config_item.is_enabled)
        self.set_container_visible(config_item.id, config_item.is_visible)

        return container

    def update_container(self, config_item: ConfigItem) -> None:
        """更新配置项容器"""
        container = self.containers.get(config_item.id)
        control = self.controls.get(config_item.id)

        if not container or not control:
            return

        # 更新控件值
        if config_item.properties.type:
            self.type_module.set_control_value(
                config_item.properties.type, control, config_item.current_value
            )

        # 更新启用状态
        self.set_container_enabled(config_item.id, config_item.is_enabled)

        # 更新可见状态
        self.set_container_visible(config_item.id, config_item.is_visible)

    def set_container_enabled(self, config_id: str, enabled: bool) -> None:
        """设置容器启用状态"""
        container = self.containers.get(config_id)
        control = self.controls.get(config_id)

        if container and control:
            container.setProperty("disabled", not enabled)
            container.style().unpolish(container)
            container.style().polish(container)
            self.type_module.set_control_enabled(control, enabled)

    def set_container_visible(self, config_id: str, visible: bool) -> None:
        """设置容器可见状态"""
        container = self.containers.get(config_id)
        if container:
            container.setVisible(visible)

    def get_control_value(self, config_id: str, config_type: str) -> Optional[Any]:
        """获取控件值"""
        control = self.controls.get(config_id)
        if control:
            return self.type_module.get_control_value(config_type, control)
        return None
